package sale.wxb.loveshopping.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import sale.wxb.loveshopping.entity.common.Result;
import sale.wxb.loveshopping.entity.common.ResultException;
import sale.wxb.loveshopping.entity.model.SysUser;
import sale.wxb.loveshopping.enums.ResponseEnum;
import sale.wxb.loveshopping.security.UserDetailEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class SecurityUtil {
    /**
     * 过滤器中返回信息
     * @param response HttpServletResponse
     * @param rt Result
     */
    public static void writeResponse(HttpServletResponse response, Result<?> rt) throws IOException {
        String json = new ObjectMapper().writeValueAsString(rt);
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().print(json);
    }

    /**
     * 从securityContextHolder中获取系统用户
     * @return SysUser
     */
    public static SysUser securityContextHolderGetSysUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailEntity userDetailEntity = (UserDetailEntity) authentication.getPrincipal();
        if (Objects.isNull(userDetailEntity)) {
            throw new ResultException(ResponseEnum.SERVER_ERROR, "读取用户登录信息出错！");
        }
        return userDetailEntity.getUser();
    }
}
